package com.bwie.gateway.filters;

import com.bwie.common.constants.TokenConstants;
import com.bwie.common.utils.JwtUtils;
import com.bwie.common.utils.StringUtils;
import com.bwie.gateway.config.IgnoreWhiteConfig;
import com.bwie.gateway.utils.GatewayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Autowired
    private IgnoreWhiteConfig ignoreWhiteConfig;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取路径白名单
        List<String> whites = ignoreWhiteConfig.getWhites();
        ServerHttpRequest request = exchange.getRequest();
        //获取当前请求路径
        String path = request.getURI().getPath();
        //判断路径是否在白名单中
        if (StringUtils.matches(path,whites)){
            return chain.filter(exchange);
        }

        //从请求头中取出token
        String token = request.getHeaders().getFirst(TokenConstants.TOKEN);

        //非空判断
        if (StringUtils.isBlank(token)){
            return GatewayUtils.errorResponse(exchange,"token为空");
        }

        //合法性校验
        try {
            JwtUtils.parseToken(token);
        } catch (Exception e) {
            return GatewayUtils.errorResponse(exchange,"token不合法");
        }

        //判断token是否过期
        String userKey = JwtUtils.getUserKey(token);
        if (redisTemplate.hasKey(TokenConstants.LOGIN_TOKEN_KEY+userKey)){
            return GatewayUtils.errorResponse(exchange,"token已过期");
        }else {
            //续期
            redisTemplate.expire(TokenConstants.LOGIN_TOKEN_KEY+userKey,20, TimeUnit.MINUTES);
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
